#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import threading
import time
from datetime import datetime
import tempfile
import re
import socket
import subprocess
from scapy.all import *
# 显式导入Windows接口相关函数
from scapy.arch.windows import get_windows_if_list

class PacketCapturer:
    """
    数据包捕获类，负责捕获网络数据包
    """
    
    def __init__(self):
        """
        初始化数据包捕获器
        """
        self.is_capturing = False
        self.capture_thread = None
        self.packets = []
        self.packet_callback = None
        self.error_callback = None
        self.interface = None
        self.filter = None
        self.pcap_file = None
        self.temp_dir = tempfile.mkdtemp()
        # 添加最大内存中存储的数据包数量限制
        self.max_packets_in_memory = 10000
        # 添加定期保存标志
        self.last_save_time = time.time()
        # 添加捕获状态监控
        self.last_packet_time = None
        self.packet_count = 0
        
    def get_interfaces(self):
        """
        获取系统上可用的网络接口列表
        
        Returns:
            list: 包含字典的列表，每个字典包含接口名称、描述和地址信息
        """
        try:
            interfaces = []
            
            # 使用scapy获取网络接口
            if os.name == 'nt':  # Windows系统
                try:
                    # 尝试导入get_windows_if_list函数
                    try:
                        from scapy.arch.windows import get_windows_if_list
                    except ImportError:
                        # 如果无法导入，尝试从scapy.arch中导入
                        try:
                            from scapy.arch import get_windows_if_list
                        except ImportError:
                            # 如果仍然失败，使用备用方法
                            if self.error_callback:
                                self.error_callback("无法导入get_windows_if_list函数，使用备用方法获取接口")
                            return self._get_windows_interfaces_backup()
                    
                    # 使用scapy的get_windows_if_list函数获取Windows接口
                    win_interfaces = get_windows_if_list()
                    
                    # 获取Windows所有接口的状态
                    iface_status = {}
                    try:
                        # 使用ipconfig获取接口状态信息
                        result = subprocess.run(
                            ["ipconfig", "/all"], 
                            capture_output=True, 
                            text=True, 
                            encoding='gbk', 
                            errors='ignore'
                        )
                        
                        if result.returncode == 0:
                            current_iface = None
                            for line in result.stdout.splitlines():
                                line = line.strip()
                                # 开始新接口的描述
                                if line and "适配器" in line and ":" in line:
                                    current_iface = line.split(":")[0].strip()
                                    iface_status[current_iface] = {
                                        'status': '未知',
                                        'mac': '',
                                        'ipv4': [],
                                        'ipv6': [],
                                        'mtu': ''
                                    }
                                # 获取MAC地址
                                elif current_iface and "物理地址" in line and ":" in line:
                                    mac = line.split(":", 1)[1].strip()
                                    iface_status[current_iface]['mac'] = mac
                                # 获取连接状态
                                elif current_iface and "媒体状态" in line and ":" in line:
                                    status = line.split(":", 1)[1].strip()
                                    if "已连接" in status:
                                        iface_status[current_iface]['status'] = '已连接'
                                    else:
                                        iface_status[current_iface]['status'] = '未连接'
                                # 获取IPv4地址
                                elif current_iface and "IPv4 地址" in line and ":" in line:
                                    ipv4 = line.split(":", 1)[1].strip()
                                    if "(" in ipv4:
                                        ipv4 = ipv4.split("(")[0].strip()
                                    iface_status[current_iface]['ipv4'].append(ipv4)
                                # 获取IPv6地址
                                elif current_iface and "IPv6 地址" in line and ":" in line:
                                    ipv6 = line.split(":", 1)[1].strip()
                                    if "(" in ipv6:
                                        ipv6 = ipv6.split("(")[0].strip()
                                    iface_status[current_iface]['ipv6'].append(ipv6)
                    except Exception as e:
                        if self.error_callback:
                            self.error_callback(f"获取接口状态失败: {str(e)}")
                    
                    # 处理每个接口
                    for iface in win_interfaces:
                        name = iface.get('name', 'Unknown')
                        desc = iface.get('description', 'Unknown')
                        
                        # 检查是否是以太网接口
                        is_ethernet = "ethernet" in desc.lower() or "以太网" in desc.lower()
                        is_wireless = "wireless" in desc.lower() or "wi-fi" in desc.lower() or "无线" in desc.lower()
                        
                        # 获取IP地址
                        ip_addresses = []
                        ipv6_addresses = []
                        
                        if 'ips' in iface:
                            ip_addresses = [ip for ip in iface['ips'] if ip != '127.0.0.1']
                        
                        # 查找接口状态
                        status = "未知"
                        mac_address = ""
                        for adapter_name, adapter_info in iface_status.items():
                            # 尝试匹配接口名称或描述
                            if desc in adapter_name or any(ip in adapter_name for ip in ip_addresses):
                                status = adapter_info['status']
                                mac_address = adapter_info['mac']
                                # 添加IPv6地址
                                if adapter_info['ipv6']:
                                    ipv6_addresses = adapter_info['ipv6']
                                break
                        
                        # 确定接口类型
                        iface_type = "其他"
                        if is_ethernet:
                            iface_type = "以太网"
                        elif is_wireless:
                            iface_type = "无线"
                        elif "loopback" in name.lower() or "loop" in name.lower():
                            iface_type = "回环"
                        elif "virtual" in desc.lower() or "虚拟" in desc.lower():
                            iface_type = "虚拟"
                        elif "bluetooth" in desc.lower() or "蓝牙" in desc.lower():
                            iface_type = "蓝牙"
                        
                        interfaces.append({
                            'name': name,
                            'description': desc,
                            'addresses': ip_addresses,
                            'ipv6_addresses': ipv6_addresses,
                            'mac_address': mac_address,
                            'status': status,
                            'type': iface_type,
                            'is_ethernet': is_ethernet,
                            'is_wireless': is_wireless,
                            'is_virtual': "virtual" in desc.lower() or "虚拟" in desc.lower(),
                            'is_loopback': "loopback" in name.lower() or "loop" in name.lower()
                        })
                    
                except Exception as e:
                    if self.error_callback:
                        self.error_callback(f"获取Windows接口失败: {str(e)}")
                    # 使用备用方法
                    return self._get_windows_interfaces_backup()
            else:  # Linux/Mac系统
                try:
                    # 获取所有接口的详细信息
                    iface_details = {}
                    
                    try:
                        # 使用ip命令获取接口详情
                        result = subprocess.run(
                            ["ip", "-o", "addr"], 
                            capture_output=True, 
                            text=True
                        )
                        
                        if result.returncode == 0:
                            for line in result.stdout.splitlines():
                                parts = line.strip().split()
                                if len(parts) >= 4:
                                    iface_name = parts[1]
                                    if iface_name not in iface_details:
                                        iface_details[iface_name] = {
                                            'status': '未知',
                                            'mac': '',
                                            'ipv4': [],
                                            'ipv6': [],
                                            'mtu': ''
                                        }
                                    
                                    # 处理IP地址
                                    addr_info = " ".join(parts[3:])
                                    if "inet " in addr_info:
                                        # IPv4地址
                                        ipv4 = addr_info.split()[1].split('/')[0]
                                        if ipv4 != '127.0.0.1':
                                            iface_details[iface_name]['ipv4'].append(ipv4)
                                    elif "inet6 " in addr_info:
                                        # IPv6地址
                                        ipv6 = addr_info.split()[1].split('/')[0]
                                        if not ipv6.startswith('::1'):
                                            iface_details[iface_name]['ipv6'].append(ipv6)
                        
                        # 获取接口状态和MAC地址
                        result = subprocess.run(
                            ["ip", "-o", "link"], 
                            capture_output=True, 
                            text=True
                        )
                        
                        if result.returncode == 0:
                            for line in result.stdout.splitlines():
                                parts = line.strip().split()
                                if len(parts) >= 4:
                                    iface_name = parts[1].rstrip(':')
                                    if iface_name in iface_details:
                                        # 检查状态
                                        if "UP" in line:
                                            iface_details[iface_name]['status'] = '已连接'
                                        else:
                                            iface_details[iface_name]['status'] = '未连接'
                                        
                                        # 获取MAC地址
                                        for i, part in enumerate(parts):
                                            if part.lower() == "link/ether":
                                                if i+1 < len(parts):
                                                    iface_details[iface_name]['mac'] = parts[i+1]
                                                break
                    except Exception as e:
                        if self.error_callback:
                            self.error_callback(f"获取Linux接口详情失败: {str(e)}")
                    
                    # 使用get_if_list获取接口列表
                    iface_list = get_if_list()
                    for iface_name in iface_list:
                        # 获取基本信息
                        is_loopback = iface_name == 'lo'
                        is_ethernet = iface_name.startswith('eth') or iface_name.startswith('en')
                        is_wireless = iface_name.startswith('wlan') or iface_name.startswith('wl')
                        
                        # 获取IP地址和状态
                        ip_addresses = []
                        ipv6_addresses = []
                        status = '未知'
                        mac_address = ''
                        
                        if iface_name in iface_details:
                            ip_addresses = iface_details[iface_name]['ipv4']
                            ipv6_addresses = iface_details[iface_name]['ipv6']
                            status = iface_details[iface_name]['status']
                            mac_address = iface_details[iface_name]['mac']
                        else:
                            # 备用方法获取IP
                            try:
                                ip = get_if_addr(iface_name)
                                if ip and ip != '127.0.0.1':
                                    ip_addresses.append(ip)
                            except:
                                pass
                        
                        # 确定接口类型
                        iface_type = "其他"
                        if is_ethernet:
                            iface_type = "以太网"
                        elif is_wireless:
                            iface_type = "无线"
                        elif is_loopback:
                            iface_type = "回环"
                        elif "vir" in iface_name:
                            iface_type = "虚拟"
                        
                        # 创建接口信息
                        interfaces.append({
                            'name': iface_name,
                            'description': f"网络接口 {iface_name}",
                            'addresses': ip_addresses,
                            'ipv6_addresses': ipv6_addresses,
                            'mac_address': mac_address,
                            'status': status,
                            'type': iface_type,
                            'is_ethernet': is_ethernet,
                            'is_wireless': is_wireless,
                            'is_virtual': "vir" in iface_name,
                            'is_loopback': is_loopback
                        })
                except Exception as e:
                    if self.error_callback:
                        self.error_callback(f"获取网络接口失败: {str(e)}")
            
            # 确保以太网接口排在前面
            ethernet_interfaces = [iface for iface in interfaces if iface.get('is_ethernet', False)]
            wireless_interfaces = [iface for iface in interfaces if iface.get('is_wireless', False)]
            loopback_interfaces = [iface for iface in interfaces if iface.get('is_loopback', False)]
            other_interfaces = [
                iface for iface in interfaces 
                if not (iface.get('is_ethernet', False) or 
                        iface.get('is_wireless', False) or 
                        iface.get('is_loopback', False))
            ]
            
            # 如果没有找到回环接口，添加一个
            if not loopback_interfaces:
                loopback_interfaces.append({
                    'name': 'lo' if os.name != 'nt' else 'Loopback',
                    'description': "回环接口",
                    'addresses': ['127.0.0.1'],
                    'ipv6_addresses': ['::1'],
                    'mac_address': '',
                    'status': '已连接',
                    'type': '回环',
                    'is_ethernet': False,
                    'is_wireless': False,
                    'is_virtual': False,
                    'is_loopback': True
                })
            
            # 合并列表，以太网和无线接口优先
            return ethernet_interfaces + wireless_interfaces + loopback_interfaces + other_interfaces
            
        except Exception as e:
            if self.error_callback:
                self.error_callback(f"获取网络接口列表失败: {str(e)}")
            
            # 返回一个基本的回环接口作为备选
            return [{
                'name': 'lo' if os.name != 'nt' else 'Loopback',
                'description': "回环接口",
                'addresses': ['127.0.0.1'],
                'ipv6_addresses': ['::1'],
                'mac_address': '',
                'status': '已连接',
                'type': '回环',
                'is_ethernet': False,
                'is_wireless': False,
                'is_virtual': False,
                'is_loopback': True
            }]
    
    def start_capture(self, interface=None, packet_filter=None, callback=None, error_callback=None):
        """
        开始捕获数据包
        
        Args:
            interface: 要捕获的网络接口，可以是接口名称字符串或包含接口信息的字典
            packet_filter: 捕获过滤器字符串（Berkeley Packet Filter语法）
            callback: 每捕获到一个数据包时调用的回调函数
            error_callback: 发生错误或状态更新时调用的回调函数
            
        Returns:
            bool: 是否成功开始捕获
        """
        if self.is_capturing:
            return False
        
        # 如果提供了error_callback，包装它以便处理捕获状态更新消息
        if error_callback:
            original_error_callback = error_callback
            def wrapped_error_callback(message, show_popup=True):
                if "已捕获" in message and "个数据包" in message:
                    # 捕获过程中的状态更新，传递show_popup=False
                    return original_error_callback(message, show_popup=False)
                else:
                    # 其他消息
                    return original_error_callback(message, show_popup)
            self.error_callback = wrapped_error_callback
        else:
            self.error_callback = error_callback
        
        # 提取接口名称
        if isinstance(interface, dict) and 'name' in interface:
            interface = interface['name']
        
        self.interface = interface
        self.filter = packet_filter
        self.packet_callback = callback
        self.packets = []
        self.packet_count = 0
        self.last_packet_time = None
        self.last_save_time = time.time()
        
        if self.error_callback:
            self.error_callback(f"开始捕获，接口: {self.interface}, 过滤器: {self.filter}")
        
        # 生成临时pcap文件路径
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        self.pcap_file = os.path.join(self.temp_dir, f"capture_{timestamp}.pcap")
        
        # 启动捕获线程
        self.is_capturing = True
        self.capture_thread = threading.Thread(target=self._capture_packets)
        self.capture_thread.daemon = True
        self.capture_thread.start()
        
        return True
    
    def stop_capture(self):
        """
        停止捕获数据包
        """
        if not self.is_capturing:
            return
        
        self.is_capturing = False
        
        if self.capture_thread and self.capture_thread.is_alive():
            self.capture_thread.join(2)  # 等待最多2秒
            
        if self.error_callback:
            self.error_callback("捕获已停止")
    
    def _capture_packets(self):
        """
        内部方法，用于在单独线程中捕获数据包
        """
        try:
            if self.error_callback:
                self.error_callback(f"开始捕获数据包，接口: {self.interface}")
            
            # 准备sniff参数
            sniff_kwargs = {}
            
            # 设置接口
            if self.interface and self.interface != 'Loopback' and 'lo' not in self.interface:
                sniff_kwargs['iface'] = self.interface
            
            # 设置过滤器
            if self.filter:
                sniff_kwargs['filter'] = self.filter
            
            # 定义包处理回调
            def packet_handler(packet):
                if not self.is_capturing:
                    return
                
                try:
                    # 更新最后一个包的时间
                    self.last_packet_time = time.time()
                    self.packet_count += 1
                    
                    # 添加到数据包列表，但控制内存使用
                    self.packets.append(packet)
                    
                    # 如果包数量超过限制，将前一半的包写入文件并从内存中移除
                    if len(self.packets) >= self.max_packets_in_memory:
                        # 将前一半的包写入临时文件
                        packets_to_save = self.packets[:len(self.packets)//2]
                        wrpcap(self.pcap_file, packets_to_save, append=True)
                        # 只保留后一半的包在内存中
                        self.packets = self.packets[len(self.packets)//2:]
                        if self.error_callback:
                            self.error_callback(f"已将 {len(packets_to_save)} 个数据包写入临时文件以节省内存", show_popup=False)
                    
                    # 定期保存以防程序崩溃
                    current_time = time.time()
                    if current_time - self.last_save_time > 30:  # 每30秒保存一次
                        if self.packets:
                            wrpcap(self.pcap_file, self.packets, append=True)
                            if self.error_callback:
                                self.error_callback(f"已定期保存 {len(self.packets)} 个数据包到临时文件", show_popup=False)
                            self.last_save_time = current_time
                    
                    # 检查是否长时间没有收到数据包，可能表明网络接口有问题
                    current_time = time.time()
                    if self.last_packet_time and self.packet_count > 0 and current_time - self.last_packet_time > 30:
                        if self.error_callback:
                            self.error_callback(f"警告: 30秒内未收到数据包，捕获可能有问题", show_popup=False)
                        self.last_packet_time = current_time  # 重置时间避免重复警告
                    
                    # 如果有回调函数，则调用
                    if self.packet_callback:
                        self.packet_callback(packet)
                except Exception as e:
                    if self.error_callback:
                        self.error_callback(f"处理数据包时出错: {str(e)}", show_popup=False)
            
            if self.error_callback:
                self.error_callback("开始捕获数据包...")
            
            # 使用sniff函数捕获数据包
            # count=0表示无限捕获，store=0表示不存储在内存中（通过prn回调处理）
            # timeout设置为2秒，确保能够响应停止请求
            while self.is_capturing:
                try:
                    sniff(
                        prn=packet_handler,
                        count=10,  # 每次捕获10个包
                        store=0,
                        timeout=2,
                        **sniff_kwargs
                    )
                    
                    # 检查是否长时间没有收到数据包，可能表明网络接口有问题
                    current_time = time.time()
                    if self.last_packet_time and self.packet_count > 0 and current_time - self.last_packet_time > 30:
                        if self.error_callback:
                            self.error_callback(f"警告: 30秒内未收到数据包，捕获可能有问题", show_popup=False)
                        self.last_packet_time = current_time  # 重置时间避免重复警告
                    
                except Exception as sniff_error:
                    if self.error_callback:
                        self.error_callback(f"捕获过程中出错: {str(sniff_error)}")
                    # 短暂暂停后继续尝试捕获
                    time.sleep(1)
                
                # 短暂暂停，检查是否需要停止
                time.sleep(0.1)
            
            # 确保所有包都被写入文件
            if self.packets:
                wrpcap(self.pcap_file, self.packets, append=True)
                
            if self.error_callback:
                self.error_callback(f"捕获完成，共捕获 {self.packet_count} 个数据包")
                
        except Exception as e:
            if self.error_callback:
                self.error_callback(f"数据包捕获错误: {str(e)}")
                
                # 提供更详细的错误信息
                import traceback
                error_details = traceback.format_exc()
                self.error_callback(f"详细错误信息: {error_details}")
                
            self.is_capturing = False
    
    def get_packets(self):
        """
        返回当前捕获的所有数据包
        """
        # 如果数据包已经被保存到文件中，尝试加载
        if self.pcap_file and os.path.exists(self.pcap_file) and self.packet_count > len(self.packets):
            try:
                # 先保存当前内存中的包
                if self.packets:
                    temp_packets = self.packets
                
                # 从文件加载所有包
                self.packets = rdpcap(self.pcap_file)
                
                # 检查是否需要合并新捕获的包
                if temp_packets and len(temp_packets) > 0:
                    # 只添加文件中不存在的包
                    existing_count = len(self.packets)
                    if existing_count < self.packet_count:
                        self.packets.extend(temp_packets[-(self.packet_count - existing_count):])
            except Exception as e:
                if self.error_callback:
                    self.error_callback(f"加载捕获文件失败: {str(e)}")
        
        return self.packets
    
    def save_capture(self, filename):
        """
        保存捕获的数据包为pcap文件
        
        Args:
            filename: 保存的文件路径
        """
        if not self.packets:
            if self.error_callback:
                self.error_callback("没有数据包可保存")
            return False
        
        try:
            # 将数据包直接写入指定文件
            wrpcap(filename, self.packets)
            return True
        except Exception as e:
            if self.error_callback:
                self.error_callback(f"保存捕获文件失败: {str(e)}")
            return False
    
    def load_capture(self, filename, callback=None):
        """
        从pcap文件加载捕获的数据包
        
        Args:
            filename: pcap文件路径
            callback: 处理每个数据包的回调函数
        """
        if not os.path.exists(filename):
            if self.error_callback:
                self.error_callback(f"文件不存在: {filename}")
            return False
        
        try:
            # 清空当前数据包列表
            self.packets = []
            
            # 读取pcap文件
            loaded_packets = rdpcap(filename)
            
            # 处理每个数据包
            for packet in loaded_packets:
                self.packets.append(packet)
                if callback:
                    callback(packet)
            
            if self.error_callback:
                self.error_callback(f"成功从文件加载 {len(self.packets)} 个数据包")
                
            return True
        except Exception as e:
            if self.error_callback:
                self.error_callback(f"加载捕获文件失败: {str(e)}")
            return False
    
    def __del__(self):
        """
        析构函数，确保资源被正确释放
        """
        self.stop_capture()
        
        # 清理临时文件
        if hasattr(self, 'pcap_file') and self.pcap_file and os.path.exists(self.pcap_file):
            try:
                os.remove(self.pcap_file)
            except:
                pass
                
        # 清理临时目录
        if hasattr(self, 'temp_dir') and os.path.exists(self.temp_dir):
            try:
                os.rmdir(self.temp_dir)
            except:
                pass
    
    def _get_windows_interfaces_backup(self):
        """
        备用方法：使用ipconfig命令获取Windows网络接口
        
        Returns:
            list: 包含字典的列表，每个字典包含接口名称、描述和地址信息
        """
        interfaces = []
        
        try:
            # 使用ipconfig获取接口信息
            result = subprocess.run(
                ["ipconfig", "/all"], 
                capture_output=True, 
                text=True, 
                encoding='gbk', 
                errors='ignore'
            )
            
            if result.returncode != 0:
                if self.error_callback:
                    self.error_callback("执行ipconfig命令失败")
                return self._get_loopback_interface()
                
            # 解析ipconfig输出
            current_iface = None
            iface_info = {}
            
            for line in result.stdout.splitlines():
                line = line.strip()
                
                # 开始新接口的描述
                if line and "适配器" in line and ":" in line:
                    # 保存上一个接口
                    if current_iface and current_iface in iface_info:
                        # 创建接口对象
                        iface_data = iface_info[current_iface]
                        
                        # 确定接口类型
                        desc = iface_data.get('description', '')
                        is_ethernet = "ethernet" in desc.lower() or "以太网" in desc.lower()
                        is_wireless = "wireless" in desc.lower() or "wi-fi" in desc.lower() or "无线" in desc.lower()
                        is_loopback = "loopback" in desc.lower() or "loop" in desc.lower()
                        is_virtual = "virtual" in desc.lower() or "虚拟" in desc.lower()
                        
                        iface_type = "其他"
                        if is_ethernet:
                            iface_type = "以太网"
                        elif is_wireless:
                            iface_type = "无线"
                        elif is_loopback:
                            iface_type = "回环"
                        elif is_virtual:
                            iface_type = "虚拟"
                        
                        interfaces.append({
                            'name': current_iface,
                            'description': desc,
                            'addresses': iface_data.get('ipv4', []),
                            'ipv6_addresses': iface_data.get('ipv6', []),
                            'mac_address': iface_data.get('mac', ''),
                            'status': iface_data.get('status', '未知'),
                            'type': iface_type,
                            'is_ethernet': is_ethernet,
                            'is_wireless': is_wireless,
                            'is_virtual': is_virtual,
                            'is_loopback': is_loopback
                        })
                    
                    # 开始新接口
                    current_iface = line.split(":")[0].strip()
                    iface_info[current_iface] = {
                        'description': current_iface,
                        'status': '未知',
                        'mac': '',
                        'ipv4': [],
                        'ipv6': [],
                    }
                    
                # 获取描述
                elif current_iface and "描述" in line and ":" in line:
                    desc = line.split(":", 1)[1].strip()
                    iface_info[current_iface]['description'] = desc
                    
                # 获取MAC地址
                elif current_iface and "物理地址" in line and ":" in line:
                    mac = line.split(":", 1)[1].strip()
                    iface_info[current_iface]['mac'] = mac
                    
                # 获取连接状态
                elif current_iface and "媒体状态" in line and ":" in line:
                    status = line.split(":", 1)[1].strip()
                    if "已连接" in status:
                        iface_info[current_iface]['status'] = '已连接'
                    else:
                        iface_info[current_iface]['status'] = '未连接'
                        
                # 获取IPv4地址
                elif current_iface and "IPv4 地址" in line and ":" in line:
                    ipv4 = line.split(":", 1)[1].strip()
                    if "(" in ipv4:
                        ipv4 = ipv4.split("(")[0].strip()
                    iface_info[current_iface]['ipv4'].append(ipv4)
                    
                # 获取IPv6地址
                elif current_iface and "IPv6 地址" in line and ":" in line:
                    ipv6 = line.split(":", 1)[1].strip()
                    if "(" in ipv6:
                        ipv6 = ipv6.split("(")[0].strip()
                    iface_info[current_iface]['ipv6'].append(ipv6)
            
            # 处理最后一个接口
            if current_iface and current_iface in iface_info:
                # 创建接口对象
                iface_data = iface_info[current_iface]
                
                # 确定接口类型
                desc = iface_data.get('description', '')
                is_ethernet = "ethernet" in desc.lower() or "以太网" in desc.lower()
                is_wireless = "wireless" in desc.lower() or "wi-fi" in desc.lower() or "无线" in desc.lower()
                is_loopback = "loopback" in desc.lower() or "loop" in desc.lower()
                is_virtual = "virtual" in desc.lower() or "虚拟" in desc.lower()
                
                iface_type = "其他"
                if is_ethernet:
                    iface_type = "以太网"
                elif is_wireless:
                    iface_type = "无线"
                elif is_loopback:
                    iface_type = "回环"
                elif is_virtual:
                    iface_type = "虚拟"
                
                interfaces.append({
                    'name': current_iface,
                    'description': desc,
                    'addresses': iface_data.get('ipv4', []),
                    'ipv6_addresses': iface_data.get('ipv6', []),
                    'mac_address': iface_data.get('mac', ''),
                    'status': iface_data.get('status', '未知'),
                    'type': iface_type,
                    'is_ethernet': is_ethernet,
                    'is_wireless': is_wireless,
                    'is_virtual': is_virtual,
                    'is_loopback': is_loopback
                })
            
            # 如果没有找到任何接口，添加回环接口
            if not interfaces:
                return self._get_loopback_interface()
                
            return interfaces
            
        except Exception as e:
            if self.error_callback:
                self.error_callback(f"备用方法获取网络接口失败: {str(e)}")
            return self._get_loopback_interface()
            
    def _get_loopback_interface(self):
        """
        返回一个基本的回环接口
        
        Returns:
            list: 包含回环接口信息的列表
        """
        return [{
            'name': 'Loopback',
            'description': "回环接口 (127.0.0.1)",
            'addresses': ['127.0.0.1'],
            'ipv6_addresses': ['::1'],
            'mac_address': '',
            'status': '已连接',
            'type': '回环',
            'is_ethernet': False,
            'is_wireless': False,
            'is_virtual': False,
            'is_loopback': True
        }] 